package controllers

import (
	"fly/global"
	"fly/helper"
	"fly/models"
	"fly/req"
	"fly/resp"
	"fly/service"
	"fmt"
	"github.com/duke-git/lancet/v2/convertor"
	"net/url"
)

// BizConfigController 启动配置
type BizConfigController struct {
	BaseController
	BizConfigService service.BizConfigService
}

// GetConfig ...
// @Title 配置
// @Description 根据id获取配置
// @Param	id path  string	true "id的key"
// @Param	token header  string false "授权Token"
// @Success 200 {object} resp.BizConfigResp
// @router /:id [get]
func (c *BizConfigController) GetConfig() {
	id, err := convertor.ToInt(c.Ctx.Input.Param(":id"))
	c.CheckReqErrorAbort(err)
	con, err := c.BizConfigService.GetConfigById(id)
	c.CheckAssertAbort(con, "未找到资源")
	r := resp.BizConfigResp{}
	c.CheckRespErrorAbort(resp.Copy2TimeResp(&r, con))
	c.Success(r)
}

// AddConfig ...
// @Title 添加配置
// @Description 添加一个新配置
// @Param token header  string	false "授权Token"
// @Param body body req.AddConfigReq true "添加配置内容"
// @Success 200 {object} resp.BizConfigResp
// @router /save [post]
func (c *BizConfigController) AddConfig() {
	con := req.AddConfigReq{}
	err := c.BindJSON(&con)
	c.CheckReqErrorAbort(err)
	c.ValidReqParams(&con)
	mConfig := models.BizConfig{}
	c.CheckRespErrorAbort(helper.CopyDeep(&mConfig, con))
	if con.ExpireTime > 0 {
		mConfig.ExpireTime = helper.Int2Time(con.ExpireTime)
	}
	if con.Id > 0 {
		old, _ := models.GetBizConfigById(con.Id)
		c.CheckReqErrorAbort(helper.RequireTrue(old != nil, "未找到资源"))
		_ = helper.CopyOut(old, con)
		err = models.UpdateBizConfigById(old, c.GetReqUserId())
	} else {
		_, err = models.AddBizConfig(&mConfig, c.GetReqUserId())
	}
	c.CheckRespErrorAbort(err)
	_ = global.DelCache(fmt.Sprintf(service.BizConfigCacheKey, con.Id))
	r := resp.BizConfigResp{}
	_ = resp.Copy2TimeResp(&r, mConfig)
	c.Success(r)
}

// Index ...
// @Title 配置查询
// @Description 配置查询
// @Param token header  string	false "授权Token"
// @Param keywords query  string false "搜索字段"
// @Param pageNum query  int false "当前页"
// @Param pageSize query  int false "每页数量"
// @Param total query  int false "数据总数"
// @Param name query  string false "查询name"
// @Param value query  string false "查询value"
// @Success 200 {object} service.Pagination
// @router / [get]
func (c *BizConfigController) Index() {
	params, _ := url.ParseQuery(c.Ctx.Request.URL.RawQuery)
	data, pagination := c.BizConfigService.GetPaginateData(params)
	var list []resp.BizConfigResp
	c.CheckRespErrorAbort(resp.Copy2TimeResp(&list, &data))
	pagination.List = list
	c.Success(pagination)
}

// Del ...
// @Title 删除
// @Description 删除配置
// @Param token header  string	false "授权Token"
// @Param path id int true "配置id"
// @Success 200 {int} "id"
// @router /:id [delete]
func (c *BizConfigController) Del() {
	id, err := convertor.ToInt(c.Ctx.Input.Param(":id"))
	c.CheckReqErrorAbort(err)
	c.CheckRespErrorAbort(models.DeleteBizConfig(id))
	_ = global.DelCache(fmt.Sprintf(service.BizConfigCacheKey, id))
	c.Success(id)
}
